// 飞机大战游戏主文件
// 核心游戏逻辑和控制器

// ES6模块导入
import { Star, Planet, Nebula } from './starfield.js';
import {
    Player,
    PlayerExplosion,
    Enemy,
    EnemyElite,
    EnemyLaserSniper,
    EnemyEliteExplosion,
    Boss,
    BossExplosion,
    BossLaser,
    Bullet,
    Laser,
    Particle,
    DeviceDetector,
    HealthPack,
    MultiShot,
    Shield,
    FireRateBooster
} from './gameObjects.js';
import { TimeManager } from './classes/TimeManager.js';
import { CanvasHealthUI } from './classes/CanvasHealthUI.js';

const initLives = 5

class AircraftWar {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameState = 'menu'; // menu, playing, paused, gameOver
        this.score = 0;
        this.lives = initLives;
        this.lastTime = 0;

        // 游戏对象数组
        this.player = null;
        this.playerExplosion = null; // 玩家爆炸效果
        this.playerDestroyed = false; // 玩家是否被摧毁
        this.enemies = [];
        this.eliteEnemies = []; // 精英敌机数组
        this.laserSnipers = []; // 激光狙击手数组
        this.eliteExplosions = []; // 精英敌机爆炸效果数组
        this.boss = null; // BOSS对象
        this.bossExplosion = null; // BOSS爆炸效果
        this.bossLasers = []; // BOSS激光数组
        this.bossLevel = 1; // BOSS等级
        this.bossActive = false; // BOSS是否活跃
        this.nextBossScore = 1000; // 下个BOSS将在达到此分数时出现
        this.playerBullets = [];
        this.enemyBullets = [];
        this.lasers = []; // 激光数组
        this.particles = [];
        this.powerUps = []; // 新增道具数组

        // Canvas血量UI
        this.canvasHealthUI = null;

        // 星空背景系统
        this.stars = [];
        this.planets = [];
        this.nebula = [];

        // 输入状态
        this.keys = {};

        // 移动端触屏控制
        this.isMobileDevice = DeviceDetector.isMobileDevice();
        this.touchEnabled = DeviceDetector.isTouchSupported();
        this.touchActive = false;        // 触屏是否激活
        this.touchStartX = 0;           // 触摸开始时的X坐标
        this.touchStartY = 0;           // 触摸开始时的Y坐标
        this.touchCurrentX = 0;         // 当前触摸点X坐标
        this.touchCurrentY = 0;         // 当前触摸点Y坐标
        this.touchOffsetX = 0;          // 触摸偏移量X
        this.touchOffsetY = 0;          // 触摸偏移量Y
        this.playerStartX = 0;          // 玩家开始拖动时的X位置
        this.playerStartY = 0;          // 玩家开始拖动时的Y位置

        // 射击控制
        this.lastShootTime = 0;
        this.shootCooldown = 150; // 射击间隔时间（毫秒）

        // 游戏设置
        this.enemySpawnRate = 0.02;
        this.eliteSpawnRate = 0.003; // 精英敌机生成率（更低）
        this.laserSniperSpawnRate = 0.0015; // 激光狙击手生成率（最低）
        this.enemyShootRate = 0.0025; // 降低敌机子弹发射频率50%：从0.005降到0.0025

        this.init();
    }

    init() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');

        // 初始化画布尺寸
        this.resizeCanvas();

        this.setupEventListeners();
        this.initPlayer();
        this.initStarfield(); // 初始化星空背景

        // 初始化血量UI
        this.initCanvasHealthUI();

        // 开始游戏循环
        this.gameLoop();
    }

    setupEventListeners() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.keys[e.key.toLowerCase()] = true;
            if (e.key === ' ') {
                e.preventDefault(); // 防止页面滚动
            }
        });

        document.addEventListener('keyup', (e) => {
            this.keys[e.key.toLowerCase()] = false;
        });

        // 窗口焦点事件（自动暂停）
        window.addEventListener('blur', () => {
            if (this.gameState === 'playing') {
                this.togglePause();
            }
        });

        window.addEventListener('focus', () => {
            // 焦点回来时不自动恢复，让用户手动点击恢复
        });

        // 窗口尺寸变化事件
        window.addEventListener('resize', () => {
            this.resizeCanvas();
            // 重新初始化星空背景以适应新尺寸
            this.initStarfield();
            // 重新初始化玩家位置
            if (this.player) {
                this.player.x = Math.min(this.player.x, this.canvas.width - this.player.width);
                this.player.y = Math.min(this.player.y, this.canvas.height - this.player.height);
            }
        });

        // 按钮事件
        document.getElementById('start-btn').addEventListener('click', () => {
            this.startGame();
        });

        document.getElementById('pause-btn').addEventListener('click', () => {
            this.togglePause();
        });

        document.getElementById('resume-btn').addEventListener('click', () => {
            this.resumeGame();
        });

        document.getElementById('restart-btn').addEventListener('click', () => {
            this.restartGame();
        });

        document.getElementById('restart-game-btn').addEventListener('click', () => {
            this.restartGame();
        });

        // 触屏事件（仅在移动端启用）
        if (this.isMobileDevice && this.touchEnabled) {
            this.setupTouchEventListeners();
            console.log('移动端触屏控制已启用');
        } else {
            console.log('桌面端键盘控制模式');
        }
    }

    setupTouchEventListeners() {
        // 触屏开始事件
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault(); // 阻止默认的滚动行为

            if (this.gameState !== 'playing' || this.playerDestroyed) return;

            const touch = e.touches[0];
            const rect = this.canvas.getBoundingClientRect();

            // 转换触摸坐标为画布坐标
            this.touchStartX = (touch.clientX - rect.left) * (this.canvas.width / rect.width);
            this.touchStartY = (touch.clientY - rect.top) * (this.canvas.height / rect.height);
            this.touchCurrentX = this.touchStartX;
            this.touchCurrentY = this.touchStartY;

            // 记录玩家开始拖动时的位置
            this.playerStartX = this.player.x;
            this.playerStartY = this.player.y;

            this.touchActive = true;

        }, { passive: false });

        // 触屏移动事件
        this.canvas.addEventListener('touchmove', (e) => {
            e.preventDefault(); // 阻止默认的滚动行为

            if (!this.touchActive || this.gameState !== 'playing' || this.playerDestroyed) return;

            const touch = e.touches[0];
            const rect = this.canvas.getBoundingClientRect();

            // 转换触摸坐标为画布坐标
            this.touchCurrentX = (touch.clientX - rect.left) * (this.canvas.width / rect.width);
            this.touchCurrentY = (touch.clientY - rect.top) * (this.canvas.height / rect.height);

            // 计算偏移量
            this.touchOffsetX = this.touchCurrentX - this.touchStartX;
            this.touchOffsetY = this.touchCurrentY - this.touchStartY;

        }, { passive: false });

        // 触屏结束事件
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();

            this.touchActive = false;
            this.touchOffsetX = 0;
            this.touchOffsetY = 0;

        }, { passive: false });

        // 触屏取消事件（如来电等中断）
        this.canvas.addEventListener('touchcancel', (e) => {
            e.preventDefault();

            this.touchActive = false;
            this.touchOffsetX = 0;
            this.touchOffsetY = 0;

            console.log('触屏取消');
        }, { passive: false });

        // 禁用画布的上下文菜单（长按菜单）
        this.canvas.addEventListener('contextmenu', (e) => {
            e.preventDefault();
        });

        // 阻止双击缩放
        this.canvas.addEventListener('gesturestart', (e) => {
            e.preventDefault();
        });

        this.canvas.addEventListener('gesturechange', (e) => {
            e.preventDefault();
        });

        this.canvas.addEventListener('gestureend', (e) => {
            e.preventDefault();
        });
    }

    resizeCanvas() {
        // 获取游戏区域的实际尺寸
        const gameArea = document.querySelector('.game-area');
        const rect = gameArea.getBoundingClientRect();

        // 获取设备像素比
        const dpr = window.devicePixelRatio || 1;

        // 设置画布的CSS显示尺寸
        this.canvas.style.width = rect.width + 'px';
        this.canvas.style.height = rect.height + 'px';

        // 设置画布的实际像素尺寸（不考虑设备像素比，使用逻辑像素）
        this.canvas.width = Math.floor(rect.width);
        this.canvas.height = Math.floor(rect.height);

        // 重置画布变换
        this.ctx.setTransform(1, 0, 0, 1, 0, 0);

        // console.log(`画布尺寸调整为: ${this.canvas.width} x ${this.canvas.height} (逻辑像素), 显示: ${rect.width} x ${rect.height}, DPR: ${dpr}`);
    }

    initPlayer() {
        this.player = new Player(this.canvas.width / 2, this.canvas.height - 80);
    }

    initCanvasHealthUI() {
        // 初始化Canvas血量UI管理器，使用初始生命值
        this.canvasHealthUI = new CanvasHealthUI(initLives);
        console.log(`Canvas血量UI初始化完成，最大血量: ${initLives}`);
    }

    initStarfield() {
        console.log('初始化星空背景...');

        // 初始化星星（按层次分组，远慢近快）
        this.stars = [];

        // 远景星星（小而慢）
        for (let i = 0; i < 30; i++) {
            this.stars.push(new Star(
                Math.random() * this.canvas.width,
                Math.random() * this.canvas.height,
                Math.random() * 1 + 0.3, // 很小
                Math.random() * 0.01 + 0.005,
                Math.random() * 0.5 + 0.3 // 很慢（0.3-0.8像素/帧）
            ));
        }

        // 中景星星（中等大小和速度）
        for (let i = 0; i < 30; i++) {
            this.stars.push(new Star(
                Math.random() * this.canvas.width,
                Math.random() * this.canvas.height,
                Math.random() * 1.5 + 0.8, // 中等
                Math.random() * 0.015 + 0.008,
                Math.random() * 1 + 1 // 中等（1-2像素/帧）
            ));
        }

        console.log(`创建了 ${this.stars.length} 颗星星（分为3个层次）`);

        // 初始化星球（更小尺寸，添加星环）
        this.planets = [];
        for (let i = 0; i < 2; i++) {
            this.planets.push(new Planet(
                Math.random() * this.canvas.width,
                Math.random() * this.canvas.height,
                Math.random() * 40 + 20, // 减小尺寸（20-60像素）
                ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7'][Math.floor(Math.random() * 5)],
                Math.random() * 0.3 + 0.2, // 中等速度移动（0.2-0.5像素/帧）
                Math.random() > 0.5 // 50%概率有星环
            ));
        }
        console.log(`创建了 ${this.planets.length} 个星球`);

        // 初始化星云（最慢的移动）
        this.nebula = [];
        for (let i = 0; i < 3; i++) {
            this.nebula.push(new Nebula(
                Math.random() * this.canvas.width,
                Math.random() * this.canvas.height,
                Math.random() * 100 + 60,
                Math.random() * 0.15 + 0.05 // 最慢移动（0.05-0.2像素/帧）
            ));
        }
        console.log(`创建了 ${this.nebula.length} 个星云`);
        console.log('星空背景初始化完成!');
    }

    startGame() {
        this.gameState = 'playing';
        this.score = 0;
        this.lives = initLives;
        this.playerDestroyed = false; // 重置玩家摧毁状态
        this.playerExplosion = null; // 重置玩家爆炸效果
        this.enemies = [];
        this.eliteEnemies = []; // 重置BOSS精英敌机数组
        this.laserSnipers = []; // 重置激光狙击手数组
        this.eliteExplosions = []; // 重置精英爆炸效果数组
        this.boss = null; // 重置BOSS
        this.bossExplosion = null; // 重置BOSS爆炸效果
        this.bossLevel = 1; // 重置BOSS等级
        this.bossActive = false; // 重置BOSS状态
        this.nextBossScore = 1000; // 重置下个BOSS分数
        this.playerBullets = [];
        this.enemyBullets = [];
        this.lasers = []; // 重置激光数组
        this.particles = [];
        this.powerUps = []; // 重置道具数组

        this.initPlayer();

        // 重置保护罩充能
        if (this.player) {
            this.player.shieldCharges = 0;
            this.player.shieldActive = false;
        }

        // 重置Canvas血量UI
        if (this.canvasHealthUI) {
            this.canvasHealthUI.setMaxHealth(initLives);
            this.canvasHealthUI.setCurrentHealth(initLives);
            this.canvasHealthUI.setShieldCharges(0);
        }

        this.updateUI();

        document.getElementById('start-screen').style.display = 'none';
        document.getElementById('pause-screen').style.display = 'none';
        document.getElementById('game-over-screen').style.display = 'none';
    }

    togglePause() {
        if (this.gameState === 'playing') {
            this.gameState = 'paused';
            document.getElementById('pause-screen').style.display = 'flex';
        }
    }

    resumeGame() {
        this.gameState = 'playing';
        document.getElementById('pause-screen').style.display = 'none';
    }

    restartGame() {
        this.startGame();
    }

    gameOver() {
        this.gameState = 'gameOver';
        document.getElementById('final-score').textContent = this.score;
        document.getElementById('game-over-screen').style.display = 'flex';
    }

    updateUI() {
        document.getElementById('score').textContent = this.score;
    }

    playerShoot() {
        const currentTime = Date.now();
        // 检查射击冷却时间
        if (currentTime - this.lastShootTime < this.shootCooldown) {
            return; // 冷却中，不能射击
        }

        this.lastShootTime = currentTime;

        if (this.player.multishotActive) {
            // 多发装置激活：发射三发子弹
            const bullets = [
                new Bullet(
                    this.player.x + this.player.width / 2 - 2,
                    this.player.y - 10,
                    0, -8, 'player'
                ),
                new Bullet(
                    this.player.x + this.player.width / 2 - 2,
                    this.player.y - 10,
                    -2, -8, 'player' // 左斜射
                ),
                new Bullet(
                    this.player.x + this.player.width / 2 - 2,
                    this.player.y - 10,
                    -1, -8, 'player' // 左斜射
                ),
                new Bullet(
                    this.player.x + this.player.width / 2 - 2,
                    this.player.y - 10,
                    2, -8, 'player' // 右斜射
                ),
                new Bullet(
                    this.player.x + this.player.width / 2 - 2,
                    this.player.y - 10,
                    1, -8, 'player' // 右斜射
                )
            ];
            this.playerBullets.push(...bullets);
        } else {
            // 正常单发子弹
            const bullet = new Bullet(
                this.player.x + this.player.width / 2 - 2,
                this.player.y - 10,
                0, -8, 'player'
            );
            this.playerBullets.push(bullet);
        }
    }

    handleTouchControl() {
        // 仅在移动端且触屏激活时处理
        if (!this.isMobileDevice || !this.touchActive) {
            return;
        }

        // 根据触摸偏移量更新玩家位置
        const newX = this.playerStartX + this.touchOffsetX;
        const newY = this.playerStartY + this.touchOffsetY;

        // 边界检测和位置更新
        this.player.x = Math.max(0, Math.min(this.canvas.width - this.player.width, newX));
        this.player.y = Math.max(0, Math.min(this.canvas.height - this.player.height, newY));

        // 记录水平移动速度用于倾斜效果
        this.player.horizontalVelocity = this.touchOffsetX * 0.3; // 适当缩放偏移量

    }

    spawnEnemy() {
        // 检查是否需要生成BOSS
        this.checkBossSpawn();

        // 如果BOSS存在，停止生成其他敌机
        if (this.bossActive) {
            return;
        }

        if (Math.random() < this.enemySpawnRate) {
            const enemy = new Enemy(
                Math.random() * (this.canvas.width - 40) + 20,
                -30
            );
            this.enemies.push(enemy);
        }

        // 精英敌机生成
        if (Math.random() < this.eliteSpawnRate) {
            const eliteEnemy = new EnemyElite(
                Math.random() * (this.canvas.width - 60) + 30, // 考虑更大的宽度
                -50
            );
            this.eliteEnemies.push(eliteEnemy);
        }
        
        // 激光狙击手生成
        if (Math.random() < this.laserSniperSpawnRate) {
            const laserSniper = new EnemyLaserSniper(
                Math.random() * (this.canvas.width - 80) + 40, // 考虑更大的宽度
                -60
            );
            this.laserSnipers.push(laserSniper);
        }
    }

    // 检查是否需要生成BOSS
    checkBossSpawn() {
        if (!this.bossActive && this.score >= this.nextBossScore) {
            this.spawnBoss();
        }
    }

    // 生成BOSS
    spawnBoss() {
        const bossX = this.canvas.width / 2 - 75; // 居中位置（BOSS宽度150）
        const bossY = 50; // 从上方出现

        this.boss = new Boss(bossX, bossY, this.bossLevel);
        this.bossActive = true;

        // 不清除现有敌机，让它们继续存在
        // 新敌机的生成已在spawnEnemy()方法中通过bossActive检查停止

        console.log(`BOSS Level ${this.bossLevel} 出现！分数: ${this.score}`);
    }

    spawnPowerUp(x, y) {
        // 随机选择道具类型
        const powerUpTypes = ['health', 'multishot', 'shield'];
        const type = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];

        let powerUp;
        switch (type) {
            case 'health':
                powerUp = new HealthPack(x - 12, y - 12);
                break;
            case 'multishot':
                powerUp = new MultiShot(x - 12, y - 12);
                break;
            case 'shield':
                powerUp = new Shield(x - 12, y - 12);
                break;
        }

        this.powerUps.push(powerUp);
    }

    spawnBossPowerUp(x, y) {
        // BOSS掉落特殊道具：永久射击频率提升
        const powerUp = new FireRateBooster(x - 12, y - 12);
        this.powerUps.push(powerUp);

        console.log('️BOSS掉落了特殊道具：永久射击频率提升！');
    }

    enemyShoot(enemy) {
        if (Math.random() < this.enemyShootRate) {
            const bullet = new Bullet(
                enemy.x + enemy.width / 2 - 2, // 居中对齐子弹
                enemy.y + 15,
                0, 2.5, 'enemy' // 降低敌机子弹飞行速度：从4降到2.5
            );
            this.enemyBullets.push(bullet);
        }
    }

    // 精英敌机三连发射击
    eliteEnemyShoot(eliteEnemy) {
        if (eliteEnemy.canShoot()) {
            // 三连发子弹：中间、左斜、右斜
            const bullets = [
                new Bullet(
                    eliteEnemy.x + eliteEnemy.width / 2 - 2,
                    eliteEnemy.y + 40,
                    0, 3, 'enemy' // 中间直射
                ),
                new Bullet(
                    eliteEnemy.x + eliteEnemy.width / 2 - 2,
                    eliteEnemy.y + 40,
                    -2, 3, 'enemy' // 左斜射
                ),
                new Bullet(
                    eliteEnemy.x + eliteEnemy.width / 2 - 2,
                    eliteEnemy.y + 40,
                    2, 3, 'enemy' // 右斜射
                )
            ];
            this.enemyBullets.push(...bullets);
        }
    }

    // BOSS多模式攻击
    bossShoot(boss) {
        if (boss.canShoot()) {
            // 获取玩家位置用于目标对准
            const playerX = this.player.x + this.player.width / 2;
            const playerY = this.player.y + this.player.height / 2;
            
            // 根据当前攻击模式创建子弹
            const bullets = boss.createBullets(playerX, playerY);
            
            // 将BOSS子弹数据转换为Bullet对象
            for (let bulletData of bullets) {
                const extraData = {
                    isTracking: bulletData.isTracking || false,
                    targetX: bulletData.targetX || 0,
                    targetY: bulletData.targetY || 0,
                    trackingStrength: bulletData.trackingStrength || 0.8,
                    maxSpeed: (bulletData.maxSpeed || 2.0) * 60 // 转换为像素/秒
                };
                
                const bullet = new Bullet(
                    bulletData.x,
                    bulletData.y,
                    bulletData.vx,
                    bulletData.vy,
                    bulletData.type,
                    extraData
                );
                this.enemyBullets.push(bullet);
            }
        }
        
        // 单独处理激光攻击（不依赖canShoot）
        const laserInfo = boss.getLaserInfo();
        if (laserInfo) {
            if (laserInfo.charging && this.bossLasers.length === 0) {
                // 创建新激光（只在没有激光时创建）
                const laser = new BossLaser(laserInfo.x, laserInfo.y, laserInfo.angle, laserInfo.length);
                laser.startCharging();
                this.bossLasers.push(laser);
                console.log('创建 BOSS 激光，开始充能');
            }
        }
    }

    checkCollisions() {
        // 玩家子弹击中敌机
        for (let i = this.playerBullets.length - 1; i >= 0; i--) {
            const bullet = this.playerBullets[i];
            for (let j = this.enemies.length - 1; j >= 0; j--) {
                const enemy = this.enemies[j];
                if (this.isColliding(bullet, enemy)) {
                    this.playerBullets.splice(i, 1);
                    this.enemies.splice(j, 1);
                    this.score += 10;
                    this.createExplosion(enemy.x, enemy.y);

                    // 道具掉落检测（25%概率）
                    if (Math.random() < 0.25) {
                        this.spawnPowerUp(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                    }

                    break;
                }
            }
        }

        // 玩家子弹击中精英敌机
        for (let i = this.playerBullets.length - 1; i >= 0; i--) {
            const bullet = this.playerBullets[i];
            for (let j = this.eliteEnemies.length - 1; j >= 0; j--) {
                const eliteEnemy = this.eliteEnemies[j];
                if (this.isColliding(bullet, eliteEnemy)) {
                    this.playerBullets.splice(i, 1);

                    // 精英敌机受伤处理
                    if (eliteEnemy.takeDamage()) {
                        // 被击毁
                        this.eliteEnemies.splice(j, 1);
                        this.score += 50; // 精英敌机给更多分数
                        this.createEliteExplosion(eliteEnemy.x + eliteEnemy.width / 2, eliteEnemy.y + eliteEnemy.height / 2); // 使用精英爆炸效果

                        // 更高的道具掉落率（50%）
                        if (Math.random() < 0.5) {
                            this.spawnPowerUp(eliteEnemy.x + eliteEnemy.width / 2, eliteEnemy.y + eliteEnemy.height / 2);
                        }
                    }

                    break;
                }
            }
        }
        
        // 玩家子弹击中激光狙击手
        for (let i = this.playerBullets.length - 1; i >= 0; i--) {
            const bullet = this.playerBullets[i];
            for (let j = this.laserSnipers.length - 1; j >= 0; j--) {
                const laserSniper = this.laserSnipers[j];
                if (this.isColliding(bullet, laserSniper)) {
                    this.playerBullets.splice(i, 1);

                    // 激光狙击手受伤处理
                    if (laserSniper.takeDamage()) {
                        // 被击毁
                        this.laserSnipers.splice(j, 1);
                        this.score += 100; // 激光狙击手给更多分数
                        this.createEliteExplosion(laserSniper.x + laserSniper.width / 2, laserSniper.y + laserSniper.height / 2); // 使用精英爆炸效果

                        // 高道具掉落率（75%）
                        if (Math.random() < 0.75) {
                            this.spawnPowerUp(laserSniper.x + laserSniper.width / 2, laserSniper.y + laserSniper.height / 2);
                        }
                    }

                    break;
                }
            }
        }

        // 敌机子弹击中玩家
        for (let i = this.enemyBullets.length - 1; i >= 0; i--) {
            const bullet = this.enemyBullets[i];
            if (this.isColliding(bullet, this.player) && !this.playerDestroyed) {
                this.enemyBullets.splice(i, 1);

                // 使用玩家的onHit方法处理受击
                if (this.player.onHit()) {
                    this.lives--;
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(1);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        // 玩家被摧毁，创建爆炸效果
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
                break;
            }
        }

        // 敌机撞击玩家
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            if (this.isColliding(enemy, this.player) && !this.playerDestroyed) {
                // 使用玩家的onHit方法处理受击
                if (this.player.onHit()) {
                    this.lives--;
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(1);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        // 玩家被摧毁，创建爆炸效果
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
                // 敌机撞击玩家后不消失，继续存在
            }
        }

        // 精英敌机撞击玩家
        for (let i = this.eliteEnemies.length - 1; i >= 0; i--) {
            const eliteEnemy = this.eliteEnemies[i];
            if (this.isColliding(eliteEnemy, this.player) && !this.playerDestroyed) {
                // 使用玩家的onHit方法处理受击
                if (this.player.onHit()) {
                    this.lives--;
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(1);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        // 玩家被摧毁，创建爆炸效果
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
                // 精英敌机撞击玩家后不消失，继续存在
            }
        }

        // 玩家子弹击中BOSS
        if (this.boss && !this.boss.isDying) {
            for (let i = this.playerBullets.length - 1; i >= 0; i--) {
                const bullet = this.playerBullets[i];
                if (this.isColliding(bullet, this.boss)) {
                    this.playerBullets.splice(i, 1);

                    // BOSS受伤处理
                    if (this.boss.takeDamage()) {
                        // BOSS开始死亡序列
                        this.score += 500 + this.bossLevel * 200; // BOSS给大量分数
                    }
                    break;
                }
            }
        }

        // BOSS撞击玩家
        if (this.boss && !this.boss.isDying && this.isColliding(this.boss, this.player) && !this.playerDestroyed) {
            // 使用玩家的onHit方法处理受击
            if (this.player.onHit()) {
                this.lives--;
                if (this.lives <= 0) {
                    // 玩家被摧毁，创建爆炸效果
                    this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                } else {
                    // 普通受击爆炸
                    this.createExplosion(this.player.x, this.player.y);
                }
            }
            // BOSS撞击玩家后不消失，继续存在
        }
        
        // 激光狙击手撞击玩家
        for (let i = this.laserSnipers.length - 1; i >= 0; i--) {
            const laserSniper = this.laserSnipers[i];
            if (this.isColliding(laserSniper, this.player) && !this.playerDestroyed) {
                // 使用玩家的onHit方法处理受击
                if (this.player.onHit()) {
                    this.lives--;
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(1);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        // 玩家被摧毁，创建爆炸效果
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
                // 激光狙击手撞击玩家后不消失，继续存在
            }
        }
        
        // 激光击中玩家
        for (let i = this.lasers.length - 1; i >= 0; i--) {
            const laser = this.lasers[i];
            if (laser.checkCollision(this.player) && !this.playerDestroyed) {
                // 激光造成更高伤害
                if (this.player.onHit()) {
                    this.lives -= 2; // 激光伤害2点生命
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(2);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
                // 激光不会被摧毁，持续伤害
            }
        }
        
        // BOSS激光击中玩家
        for (let i = this.bossLasers.length - 1; i >= 0; i--) {
            const laser = this.bossLasers[i];
            if (laser.checkCollision(this.player.getCollisionBox()) && laser.canDamage() && !this.playerDestroyed) {
                // BOSS激光造成更高伤害
                if (this.player.onHit()) {
                    this.lives -= 2; // BOSS激光伤害2点生命
                    // 更新Canvas血量UI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.takeDamage(2);
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    if (this.lives <= 0) {
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        // 普通受击爆炸
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
            }
        }

        // 玩家收集道具
        for (let i = this.powerUps.length - 1; i >= 0; i--) {
            const powerUp = this.powerUps[i];
            if (this.isColliding(this.player, powerUp)) {
                // 应用道具效果
                if (powerUp.applyEffect(this.player, this)) {
                    this.powerUps.splice(i, 1);
                    // 同步护盾状态到CanvasHealthUI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    // 加分奖励
                    this.score += 5;
                }
            }
        }
        for (let i = this.powerUps.length - 1; i >= 0; i--) {
            const powerUp = this.powerUps[i];
            if (this.isColliding(this.player, powerUp)) {
                // 应用道具效果
                if (powerUp.applyEffect(this.player, this)) {
                    this.powerUps.splice(i, 1);
                    // 同步护盾状态到CanvasHealthUI
                    if (this.canvasHealthUI) {
                        this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
                    }
                    // 加分奖励
                    this.score += 5;
                }
            }
        }
    }

    isColliding(obj1, obj2) {
        // 如果obj1是玩家，使用精确碰撞盒
        if (obj1 === this.player && this.player.getCollisionBox) {
            const playerBox = this.player.getCollisionBox();
            return playerBox.x < obj2.x + obj2.width &&
                   playerBox.x + playerBox.width > obj2.x &&
                   playerBox.y < obj2.y + obj2.height &&
                   playerBox.y + playerBox.height > obj2.y;
        }
        // 如果obj2是玩家，使用精确碰撞盒
        else if (obj2 === this.player && this.player.getCollisionBox) {
            const playerBox = this.player.getCollisionBox();
            return obj1.x < playerBox.x + playerBox.width &&
                   obj1.x + obj1.width > playerBox.x &&
                   obj1.y < playerBox.y + playerBox.height &&
                   obj1.y + obj1.height > playerBox.y;
        }
        // 默认矩形碰撞检测
        else {
            return obj1.x < obj2.x + obj2.width &&
                   obj1.x + obj1.width > obj2.x &&
                   obj1.y < obj2.y + obj2.height &&
                   obj1.y + obj1.height > obj2.y;
        }
    }

    createExplosion(x, y) {
        for (let i = 0; i < 10; i++) {
            this.particles.push(new Particle(x, y));
        }
    }

    // 创建精英敌机爆炸效果
    createEliteExplosion(x, y) {
        // 创建炫酷的精英爆炸效果
        const eliteExplosion = new EnemyEliteExplosion(x, y);
        this.eliteExplosions.push(eliteExplosion);

        // 额外创建一些普通粒子增强效果
        for (let i = 0; i < 20; i++) {
            this.particles.push(new Particle(x, y));
        }
    }

    // 创建玩家爆炸效果
    createPlayerExplosion(x, y) {
        // 创建壮观的玩家爆炸效果
        this.playerExplosion = new PlayerExplosion(x, y);
        this.playerDestroyed = true;

        // 额外创建更多粒子增强效果
        for (let i = 0; i < 30; i++) {
            this.particles.push(new Particle(x, y));
        }
    }

    // 创建BOSS爆炸效果
    createBossExplosion(x, y) {
        // 创建巨大的BOSS爆炸效果
        this.bossExplosion = new BossExplosion(x, y, this.bossLevel);

        // 额外创建更多粒子增强效果
        for (let i = 0; i < 50; i++) {
            this.particles.push(new Particle(x, y));
        }

        console.log(`BOSS Level ${this.bossLevel} 被摧毁！`);
    }

    update(deltaTime) {
        // 更新星空背景（始终更新，不受游戏状态影响）
        this.stars.forEach(star => star.update(deltaTime));
        this.planets.forEach(planet => planet.update(deltaTime));
        this.nebula.forEach(nebula => nebula.update(deltaTime));

        if (this.gameState !== 'playing') return;

        // 处理连续射击（空格键按下时，仅在玩家未被摧毁时）
        if (this.keys[' '] && !this.playerDestroyed) {
            this.playerShoot();
        }

        // 移动端自动连续射击（仅在移动端且游戏进行中时）
        if (this.isMobileDevice && !this.playerDestroyed) {
            this.playerShoot();
        }

        // 更新玩家（仅在未被摧毁时）
        if (!this.playerDestroyed) {
            // 处理触屏控制
            this.handleTouchControl();

            // 更新玩家位置
            this.player.update(this.keys, this.canvas, deltaTime);
        }

        // 生成敌机
        this.spawnEnemy();

        // 更新敌机
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            enemy.update(deltaTime);
            this.enemyShoot(enemy);

            if (enemy.y > this.canvas.height) {
                this.enemies.splice(i, 1);
            }
        }

        // 更新精英敌机
        for (let i = this.eliteEnemies.length - 1; i >= 0; i--) {
            const eliteEnemy = this.eliteEnemies[i];
            eliteEnemy.update(deltaTime);
            this.eliteEnemyShoot(eliteEnemy);

            if (eliteEnemy.y > this.canvas.height) {
                this.eliteEnemies.splice(i, 1);
            }
        }
        
        // 更新激光狙击手
        for (let i = this.laserSnipers.length - 1; i >= 0; i--) {
            const laserSniper = this.laserSnipers[i];
            const laserData = laserSniper.update(deltaTime, this.player);
            
            // 如果狙击手发射了激光
            if (laserData) {
                const laser = new Laser(
                    laserData.startX,
                    laserData.startY,
                    laserData.endX,
                    laserData.endY,
                    laserData.type
                );
                this.lasers.push(laser);
                console.log('激光狙击手发射激光！', laserData);
            }

            if (laserSniper.y > this.canvas.height) {
                this.laserSnipers.splice(i, 1);
            }
        }

        // 更新BOSS
        if (this.boss) {
            const result = this.boss.update(deltaTime, this.canvas.width, this.canvas.height);

            // 如果BOSS不在死亡状态，让它射击
            if (!this.boss.isDying) {
                this.bossShoot(this.boss);
            }

            // 检查BOSS是否需要爆炸
            if (result === 'explode') {
                this.createBossExplosion(this.boss.x + this.boss.width / 2, this.boss.y + this.boss.height / 2);
                // BOSS开始爆炸时立即掉落道具
                this.spawnBossPowerUp(this.boss.x + this.boss.width / 2, this.boss.y + this.boss.height / 2);
            }
        }

        // 更新BOSS爆炸效果
        if (this.bossExplosion) {
            // 检查玩家是否在伤害区域内
            if (this.bossExplosion.checkPlayerDamage(this.player) && !this.playerDestroyed) {
                // 玩家被BOSS爆炸伤害
                if (this.player.onHit()) {
                    this.lives--;
                    if (this.lives <= 0) {
                        this.createPlayerExplosion(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2);
                    } else {
                        this.createExplosion(this.player.x, this.player.y);
                    }
                }
            }

            if (!this.bossExplosion.update(deltaTime)) {
                // BOSS爆炸效果完成，准备下个BOSS
                this.bossExplosion = null;
                this.boss = null;
                this.bossActive = false;
                this.bossLevel++;
                this.nextBossScore += 1000; // 下个BOSS在再增加1000分后出现

                console.log(`准备下个BOSS: Level ${this.bossLevel}, 分数阈值: ${this.nextBossScore}`);
            }
        }

        // 更新子弹
        for (let i = this.playerBullets.length - 1; i >= 0; i--) {
            const bullet = this.playerBullets[i];
            bullet.update(deltaTime);
            if (bullet.y < -10) {
                this.playerBullets.splice(i, 1);
            }
        }

        for (let i = this.enemyBullets.length - 1; i >= 0; i--) {
            const bullet = this.enemyBullets[i];
            
            // 如果是追踪导弹，传递玩家位置
            if (bullet.isTracking && this.player) {
                const playerX = this.player.x + this.player.width / 2;
                const playerY = this.player.y + this.player.height / 2;
                bullet.update(deltaTime, playerX, playerY);
                console.log("1");
                
            } else {
                bullet.update(deltaTime);
            }
            
            if (bullet.y > this.canvas.height + 10 || 
                bullet.x < -10 || bullet.x > this.canvas.width + 10) {
                this.enemyBullets.splice(i, 1);
            }
        }
        
        // 更新BOSS激光
        for (let i = this.bossLasers.length - 1; i >= 0; i--) {
            const laser = this.bossLasers[i];
            
            // 获取BOSS激光信息用于角度更新
            let newAngle = null;
            if (this.boss) {
                const laserInfo = this.boss.getLaserInfo();
                if (laserInfo && laserInfo.sweeping) {
                    newAngle = laserInfo.angle;
                }
            }
            
            if (!laser.update(deltaTime, newAngle)) {
                this.bossLasers.splice(i, 1);
            }
        }
        
        // 更新激光
        for (let i = this.lasers.length - 1; i >= 0; i--) {
            const laser = this.lasers[i];
            if (!laser.update(deltaTime)) {
                this.lasers.splice(i, 1);
            }
        }

        // 更新粒子效果
        for (let i = this.particles.length - 1; i >= 0; i--) {
            const particle = this.particles[i];
            particle.update(deltaTime);
            if (TimeManager.isTimeUp(particle.life)) {
                this.particles.splice(i, 1);
            }
        }

        // 更新精英爆炸效果
        for (let i = this.eliteExplosions.length - 1; i >= 0; i--) {
            const explosion = this.eliteExplosions[i];
            if (!explosion.update(deltaTime)) {
                this.eliteExplosions.splice(i, 1);
            }
        }

        // 更新玩家爆炸效果和游戏结束检查
        if (this.playerExplosion) {
            if (!this.playerExplosion.update(deltaTime)) {
                // 玩家爆炸效果完成，结束游戏
                this.playerExplosion = null;
                this.gameOver();
            }
        }

        // 更新道具
        for (let i = this.powerUps.length - 1; i >= 0; i--) {
            const powerUp = this.powerUps[i];
            powerUp.update(deltaTime);
            if (powerUp.isOffScreen(this.canvas.height)) {
                this.powerUps.splice(i, 1);
            }
        }

        // 碰撞检测
        this.checkCollisions();

        // 更新Canvas血量UI
        if (this.canvasHealthUI) {
            this.canvasHealthUI.update(deltaTime);
            // 同步玩家护盾状态
            if (this.player) {
                this.canvasHealthUI.setShieldCharges(this.player.shieldCharges);
            }
        }

        // 更新UI
        this.updateUI();
    }

    render() {
        // 清空画布
        this.ctx.fillStyle = '#000428';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 始终绘制星空背景（不管游戏状态）
        this.drawEnhancedStarfield();

        // 只在游戏进行时绘制游戏对象
        if (this.gameState === 'playing' || this.gameState === 'paused') {
            // 只在玩家未被摧毁时绘制玩家
            if (!this.playerDestroyed) {
                this.player.render(this.ctx);
            }

            this.enemies.forEach(enemy => enemy.render(this.ctx));
            this.eliteEnemies.forEach(eliteEnemy => eliteEnemy.render(this.ctx)); // 渲染精英敌机
            this.laserSnipers.forEach(laserSniper => laserSniper.render(this.ctx)); // 渲染激光狙击手

            // 渲染BOSS
            if (this.boss) {
                this.boss.render(this.ctx);
            }

            this.playerBullets.forEach(bullet => bullet.render(this.ctx));
            this.enemyBullets.forEach(bullet => bullet.render(this.ctx));
            this.lasers.forEach(laser => laser.render(this.ctx)); // 渲染激光
            this.bossLasers.forEach(laser => laser.render(this.ctx)); // 渲染BOSS激光
            this.particles.forEach(particle => particle.render(this.ctx));
            this.eliteExplosions.forEach(explosion => explosion.render(this.ctx)); // 渲染精英爆炸效果

            // 渲染BOSS爆炸效果
            if (this.bossExplosion) {
                this.bossExplosion.render(this.ctx);
            }

            // 渲染玩家爆炸效果
            if (this.playerExplosion) {
                this.playerExplosion.render(this.ctx);
            }

            this.powerUps.forEach(powerUp => powerUp.render(this.ctx)); // 渲染道具

            // 渲染Canvas血量UI（在右上角）
            if (this.canvasHealthUI) {
                this.canvasHealthUI.render(this.ctx, this.canvas.width, this.canvas.height);
            }

            // 绘制道具状态UI（仅在玩家未被摧毁时）
            if (!this.playerDestroyed) {
                this.renderPowerUpStatus();
            }
        }
    }

    drawEnhancedStarfield() {
        // 绘制星云（在最后面）
        if (this.nebula && this.nebula.length > 0) {
            this.nebula.forEach(nebula => nebula.render(this.ctx));
        }

        // 绘制星球（中层）
        if (this.planets && this.planets.length > 0) {
            this.planets.forEach(planet => planet.render(this.ctx));
        }

        // 绘制星星（前层）
        if (this.stars && this.stars.length > 0) {
            this.stars.forEach(star => star.render(this.ctx));
        }
    }

    renderPowerUpStatus() {
        const startY = 20;
        const lineHeight = 25;
        let currentY = startY;

        this.ctx.save();
        this.ctx.font = '14px Arial';
        this.ctx.textAlign = 'left';

        // 多发装置状态
        if (this.player.multishotActive) {
            const remainingTime = Math.ceil(TimeManager.msToSeconds(this.player.multishotTime));
            const progress = TimeManager.getProgress(this.player.multishotTime, TimeManager.CONSTANTS.MULTISHOT_DURATION);

            // 背景条
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
            this.ctx.fillRect(10, currentY, 200, 20);

            // 进度条
            const gradient = this.ctx.createLinearGradient(12, currentY + 2, 12 + 196 * progress, currentY + 2);
            gradient.addColorStop(0, '#44ff44');
            gradient.addColorStop(1, '#88ff88');

            this.ctx.fillStyle = gradient;
            this.ctx.fillRect(12, currentY + 2, 196 * progress, 16);

            // 文字
            this.ctx.fillStyle = '#ffffff';
            this.ctx.fillText(`多发装置: ${remainingTime}s`, 15, currentY + 14);

            currentY += lineHeight;
        }

        // 保护罩状态（显示充能次数）
        // if (this.player.shieldActive && this.player.shieldCharges > 0) {
        //     const charges = this.player.shieldCharges;
        //     const maxCharges = 3;
        //     const progress = charges / maxCharges;

        //     // 背景条
        //     this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        //     this.ctx.fillRect(10, currentY, 200, 20);

        //     // 充能显示条
        //     const gradient = this.ctx.createLinearGradient(12, currentY + 2, 12 + 196 * progress, currentY + 2);
        //     gradient.addColorStop(0, '#4444ff');
        //     gradient.addColorStop(1, '#8888ff');

        //     this.ctx.fillStyle = gradient;
        //     this.ctx.fillRect(12, currentY + 2, 196 * progress, 16);

        //     // 绘制充能指示器（小正方形）
        //     for (let i = 0; i < maxCharges; i++) {
        //         const x = 15 + i * 65;
        //         const y = currentY + 3;

        //         if (i < charges) {
        //             // 有充能：蓝色发光
        //             this.ctx.fillStyle = '#4488ff';
        //             this.ctx.shadowBlur = 3;
        //             this.ctx.shadowColor = '#4488ff';
        //         } else {
        //             // 无充能：灰色
        //             this.ctx.fillStyle = '#666666';
        //             this.ctx.shadowBlur = 0;
        //         }

        //         this.ctx.fillRect(x, y, 14, 14);
        //     }

        //     // 重置阴影
        //     this.ctx.shadowBlur = 0;

        //     // 文字
        //     this.ctx.fillStyle = '#ffffff';
        //     this.ctx.fillText(`保护罩: ${charges}/3`, 15, currentY + 14);

        //     currentY += lineHeight;
        // }

        this.ctx.restore();
    }

    gameLoop(currentTime = 0) {
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;

        this.update(deltaTime);
        this.render();

        requestAnimationFrame((time) => this.gameLoop(time));
    }
}

// 启动游戏
document.addEventListener('DOMContentLoaded', () => {
    new AircraftWar();
});

// 导出主游戏类
export { AircraftWar };